from PyQt5 import QtCore, QtGui, QtWidgets

class Text_Editor(QtWidgets.QTextEdit):

    ID_number = 1

    def __init__(self, filename=None, parent=None):

        super(Text_Editor, self).__init__()
        self.filename = filename
        if filename == None:
            self.filename = "Untitled-{0}".format(Text_Editor.ID_number)
            Text_Editor.ID_number += 1
        self.document().setModified(False)
        self.Editor_name = QtCore.QFileInfo(self.filename).fileName()
        self.setFont(QtGui.QFont('Courier New', 10))
        self.setWindowTitle(self.Editor_name)
    
    def load_file(self):
        file = None
        with open(self.filename, mode='r+', encoding='utf-8') as file:
            self.setText(file.read())
            self.document().setModified(False)
        file.close()
    
    def save_file(self):
        if self.filename:                                                                   
            with open(self.filename, "w+") as f:
                data = self.toPlainText()                       
                f.write(data)
        f.close()


    def closeEvent(self, event):

        modified = self.document().isModified()
        # if document changed
        if modified:
            self.message = QtWidgets.QMessageBox()
            self.message.setWindowTitle("SLP")

            result = QtWidgets.QMessageBox.question(self, "SLP", "文本中的数据已发生改变，你需要保存后再退出吗？", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |QtWidgets.QMessageBox.Cancel)

            if result == QtWidgets.QMessageBox.Yes:
                self.save_file()
                event.accept()
                super().closeEvent(event)
            elif result == QtWidgets.QMessageBox.No  :
                event.accept()
                super().closeEvent(event)
            elif result == QtWidgets.QMessageBox.Cancel:
                event.ignore()
